package com.heima.wemedia.service.impl;

import com.heima.common.aliyun.GreenImageUploadScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.common.util.JsonUtils;
import com.heima.common.util.SensitiveWordUtil;
import com.heima.feign.ApArticleFeignClient;
import com.heima.file.service.MinioService;
import com.heima.model.media.dtos.WmNewsContentItem;
import com.heima.model.media.dtos.WmNewsDto;
import com.heima.model.media.dtos.WmNewsResultDTO;
import com.heima.wemedia.entity.WmNews;
import com.heima.wemedia.service.WmAuditService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmSensitiveService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service("wmAuditService")
public class WmAuditServiceImpl implements WmAuditService {

    @Autowired
    private WmNewsService newsService;

    @Autowired
    private ApArticleFeignClient articleFeignClient;

    @Autowired
    private GreenTextScan textScan;

    @Autowired
    private GreenImageUploadScan imageUploadScan;

    @Autowired
    private MinioService minioService;

    @Autowired
    private WmSensitiveService sensitiveService;

    @Autowired
    private Tess4jClient tess4jClient;


    @Override
    @Async("taskExecutor")
    public void asyncAudit(Integer wmUserId, WmNewsDto dto) {
        log.info("开始异步审核");
        // 继续处理审核的逻辑, 自动审核
        // 阿里云文本审核
        // 拿到要审核的文本内容，title、content、labels
        log.info("阿里云文本审核：wmNewsId:{}", dto.getId());
        String title = dto.getTitle();
        String content =  dto.getContent();
        String labels = dto.getLabels();
        List<WmNewsContentItem> wmNewsContentItems = JsonUtils.toList(content, WmNewsContentItem.class);
        String auditContent = wmNewsContentItems.stream()
                .filter(item-> Objects.equals(item.getType(), WmNewsContentItem.TEXT_TYPE))
                .map(item->item.getValue())
                .collect(Collectors.joining("-"));
        String auditText = title + "-" + auditContent +"-" + labels;
        try{
            Map<String, String> auditResultMap = textScan.greenTextScan(auditText);
            String auditResult = auditResultMap.get("suggestion");
            if(Objects.equals(auditResult, "pass")){
                // 通过
            }else if(Objects.equals(auditResult, "review")){
                // 待人工
                String reason = auditResultMap.get("reason");
                WmNews updateWmNews = new WmNews();
                updateWmNews.setId(dto.getId());
                updateWmNews.setStatus(3);//TODO
                updateWmNews.setReason(reason);
                newsService.updateById(updateWmNews);
                return;
            }else{
                //失败
                String reason = auditResultMap.get("reason");
                WmNews updateWmNews = new WmNews();
                updateWmNews.setId(dto.getId());
                updateWmNews.setStatus(2);//TODO
                updateWmNews.setReason(reason);
                newsService.updateById(updateWmNews);
                return;
            }
        }catch (Exception e){
            log.error("阿里云文本审核异常:{}", ExceptionUtils.getStackTrace(e));
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
        // 阿里云图片审核
        // 拿到图片，封面图 + 正文图
        log.info("阿里云图片审核：wmNewsId:{}", dto.getId());
        List<byte[]> imageBytesList = new ArrayList<>();
        try{
            // 封面图
            List<String> coverImages = dto.getImages();
            if(!CollectionUtils.isEmpty(coverImages)){
                for(String coverUrl : coverImages){
                    byte[] imageBytes = minioService.downLoadFile(coverUrl);
                    imageBytesList.add(imageBytes);
                }
            }
            // 正文图
            List<String> bodyImageUrlList = wmNewsContentItems.stream().filter(item -> Objects.equals(item.getType(), WmNewsContentItem.IMAGE_TYPE))
                    .map(item -> item.getValue())
                    .collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(bodyImageUrlList)){
                for(String bodyUrl : bodyImageUrlList){
                    byte[] imageBytes = minioService.downLoadFile(bodyUrl);
                    imageBytesList.add(imageBytes);
                }
            }
            if(!CollectionUtils.isEmpty(imageBytesList)){
                Map<String, String> imageAuditResultMap = imageUploadScan.imageScan(imageBytesList);
                String auditResult = imageAuditResultMap.get("suggestion");
                if(Objects.equals(auditResult, "pass")){
                    // 通过
                }else if(Objects.equals(auditResult, "review")){
                    // 待人工
                    String reason = imageAuditResultMap.get("label");
                    WmNews updateWmNews = new WmNews();
                    updateWmNews.setId(dto.getId());
                    updateWmNews.setStatus(3);//TODO
                    updateWmNews.setReason(reason);
                    newsService.updateById(updateWmNews);
                    return;
                }else{
                    //失败
                    String reason = imageAuditResultMap.get("label");
                    WmNews updateWmNews = new WmNews();
                    updateWmNews.setId(dto.getId());
                    updateWmNews.setStatus(2);//TODO
                    updateWmNews.setReason(reason);
                    newsService.updateById(updateWmNews);
                    return;
                }
            }
        }catch (Exception e){
            log.error("阿里云图片审核异常:{}", ExceptionUtils.getStackTrace(e));
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
        // 敏感词审核
        log.info("敏感词审核：wmNewsId:{}", dto.getId());
        List<String> sensitiveWordsList = sensitiveService.getAll();
        if(!CollectionUtils.isEmpty(sensitiveWordsList)){
            Map<String, Integer> sensitiveAuditResultMap = SensitiveWordUtil.matchWords(sensitiveWordsList, auditText);
            if(CollectionUtils.isEmpty(sensitiveAuditResultMap)){
                // 通过
            }else{
                String reason = sensitiveAuditResultMap.keySet().stream().collect(Collectors.joining(","));
                WmNews updateWmNews = new WmNews();
                updateWmNews.setId(dto.getId());
                updateWmNews.setStatus(2);//TODO
                updateWmNews.setReason(reason);
                newsService.updateById(updateWmNews);
                return;
            }
        }
        // 图片文字识别 敏感词审核
        // 拿图片，封面图 + 正文图
        log.info("图片敏感词审核：wmNewsId:{}", dto.getId());
        if(!CollectionUtils.isEmpty(imageBytesList)){
            try{
                for(byte[] imageBytes : imageBytesList){
                    BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(imageBytes));
                    String imageText = tess4jClient.doOCR(bufferedImage);
                    if(!CollectionUtils.isEmpty(sensitiveWordsList)){
                        Map<String, Integer> sensitiveAuditResultMap = SensitiveWordUtil.matchWords(sensitiveWordsList, imageText);
                        if(CollectionUtils.isEmpty(sensitiveAuditResultMap)){
                            // 通过
                        }else{
                            String reason = sensitiveAuditResultMap.keySet().stream().collect(Collectors.joining(","));
                            WmNews updateWmNews = new WmNews();
                            updateWmNews.setId(dto.getId());
                            updateWmNews.setStatus(2);//TODO
                            updateWmNews.setReason(reason);
                            newsService.updateById(updateWmNews);
                            return;
                        }
                    }
                }
            }catch(Exception e){
                log.error("图片敏感词审核异常:{}", ExceptionUtils.getStackTrace(e));
                throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
            }
        }
        // 审核通过
        log.info("审核通过，wmNewsId:{}", dto.getId());

        Date publishTime = dto.getPublishTime();
        // 如果发布时间大于当前时间，则未来发布
        if(publishTime != null && publishTime.getTime() > System.currentTimeMillis()){
            // TODO 定时发布
        }
        // 1. 把wmNews发布成article
        // 2. 回填articleId,修改状态
        // 把wmNews发布成article,feign
        WmNewsResultDTO wmNewsResultDTO = new WmNewsResultDTO();
        wmNewsResultDTO.setId(dto.getId());
        wmNewsResultDTO.setWmUserId(wmUserId);
        wmNewsResultDTO.setTitle(dto.getTitle());
        wmNewsResultDTO.setContent(dto.getContent());
        wmNewsResultDTO.setType(dto.getType());
        wmNewsResultDTO.setChannelId(dto.getChannelId());
        wmNewsResultDTO.setChannelName("ch_name");// TODO
        wmNewsResultDTO.setLabels(dto.getLabels());
        wmNewsResultDTO.setPublishTime(dto.getPublishTime());
        wmNewsResultDTO.setImages(CollectionUtils.isEmpty(dto.getImages())?null:dto.getImages().stream().collect(Collectors.joining(",")));
        Long articleId = articleFeignClient.createArticle(wmNewsResultDTO);
        //回填article_id， 修改审核状态
        WmNews updateWmNews = new WmNews();
        updateWmNews.setId(dto.getId());
        updateWmNews.setStatus(9);
        updateWmNews.setArticleId(articleId);
        newsService.updateById(updateWmNews);
    }
}
